<template>
  <div class="purchase-report">
    <!-- 页面标题和操作栏 -->
    <div class="report-header">
      <h2>采购报表</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-select v-model="supplierId" placeholder="选择供应商" style="width: 150px; margin-left: 10px;">
          <el-option label="全部供应商" value="" />
          <el-option label="供应商A" value="1" />
          <el-option label="供应商B" value="2" />
          <el-option label="供应商C" value="3" />
        </el-select>
        <el-select v-model="categoryId" placeholder="采购类别" style="width: 150px; margin-left: 10px;">
          <el-option label="全部类别" value="" />
          <el-option label="原材料" value="1" />
          <el-option label="办公用品" value="2" />
          <el-option label="设备采购" value="3" />
        </el-select>
        <el-button type="primary" @click="refreshData" style="margin-left: 10px;">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-dropdown style="margin-left: 10px;">
          <el-button type="success">
            导出 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="exportExcel">导出Excel</el-dropdown-item>
              <el-dropdown-item @click="exportPDF">导出PDF</el-dropdown-item>
              <el-dropdown-item @click="exportImage">导出图片</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button @click="printReport" style="margin-left: 10px;">
          <el-icon><Printer /></el-icon>
          打印
        </el-button>
      </div>
    </div>

    <!-- 采购关键指标 -->
    <el-row :gutter="20" class="metrics-cards">
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(totalPurchaseAmount) }}</div>
            <div class="metric-label">总采购金额</div>
            <div class="metric-change positive">+12.5%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">{{ totalOrders }}</div>
            <div class="metric-label">采购订单数</div>
            <div class="metric-change positive">+8</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">{{ supplierCount }}</div>
            <div class="metric-label">活跃供应商</div>
            <div class="metric-change neutral">0</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">{{ avgDeliveryDays }}天</div>
            <div class="metric-label">平均交货周期</div>
            <div class="metric-change negative">+2天</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 采购趋势图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>采购金额趋势</span>
          </template>
          <div ref="purchaseTrendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 供应商分布 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>供应商采购占比</span>
          </template>
          <div ref="supplierDistributionChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-section">
      <!-- 采购类别分析 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>采购类别分析</span>
          </template>
          <div ref="categoryAnalysisChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 成本分析 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>采购成本分析</span>
          </template>
          <div ref="costAnalysisChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 供应商绩效分析 -->
    <el-row :gutter="20" class="performance-section">
      <el-col :span="8">
        <el-card>
          <template #header>
            <span style="color: #67C23A;">优秀供应商</span>
          </template>
          <div class="performance-list">
            <div v-for="supplier in topSuppliers" :key="supplier.id" class="performance-item">
              <div class="supplier-info">
                <div class="supplier-name">{{ supplier.name }}</div>
                <div class="supplier-detail">采购金额: ¥{{ formatNumber(supplier.amount) }} | 准时率: {{ supplier.onTimeRate }}%</div>
              </div>
              <el-tag type="success" size="small">优秀</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <span style="color: #E6A23C;">交货延迟</span>
          </template>
          <div class="performance-list">
            <div v-for="supplier in delayedSuppliers" :key="supplier.id" class="performance-item">
              <div class="supplier-info">
                <div class="supplier-name">{{ supplier.name }}</div>
                <div class="supplier-detail">延迟订单: {{ supplier.delayedOrders }}个 | 平均延迟: {{ supplier.avgDelay }}天</div>
              </div>
              <el-tag type="warning" size="small">关注</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <span style="color: #909399;">质量问题</span>
          </template>
          <div class="performance-list">
            <div v-for="supplier in qualityIssueSuppliers" :key="supplier.id" class="performance-item">
              <div class="supplier-info">
                <div class="supplier-name">{{ supplier.name }}</div>
                <div class="supplier-detail">质量问题: {{ supplier.qualityIssues }}次 | 合格率: {{ supplier.qualityRate }}%</div>
              </div>
              <el-tag type="info" size="small">待改善</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 采购明细表格 -->
    <el-card class="data-table-card">
      <template #header>
        <span>采购明细</span>
      </template>
      <el-table :data="purchaseDetailData" stripe style="width: 100%">
        <el-table-column prop="orderNo" label="采购单号" width="150" />
        <el-table-column prop="supplierName" label="供应商" width="150" />
        <el-table-column prop="productName" label="产品名称" width="200" />
        <el-table-column prop="category" label="类别" width="120" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="orderDate" label="下单日期" width="120" />
        <el-table-column prop="deliveryDate" label="交货日期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalRecords"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, ArrowDown, Printer } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const dateRange = ref<[string, string]>(['2024-01-01', '2024-12-31'])
const supplierId = ref('')
const categoryId = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalRecords = ref(150)

// 采购关键指标
const totalPurchaseAmount = ref(2850000)
const totalOrders = ref(156)
const supplierCount = ref(28)
const avgDeliveryDays = ref(12)

// 图表引用
const purchaseTrendChart = ref()
const supplierDistributionChart = ref()
const categoryAnalysisChart = ref()
const costAnalysisChart = ref()

// 供应商绩效数据
const topSuppliers = ref([
  { id: 1, name: '优质供应商A', amount: 850000, onTimeRate: 98 },
  { id: 2, name: '可靠供应商B', amount: 650000, onTimeRate: 95 },
  { id: 3, name: '稳定供应商C', amount: 480000, onTimeRate: 92 }
])

const delayedSuppliers = ref([
  { id: 1, name: '供应商D', delayedOrders: 5, avgDelay: 3 },
  { id: 2, name: '供应商E', delayedOrders: 3, avgDelay: 5 },
  { id: 3, name: '供应商F', delayedOrders: 2, avgDelay: 7 }
])

const qualityIssueSuppliers = ref([
  { id: 1, name: '供应商G', qualityIssues: 3, qualityRate: 85 },
  { id: 2, name: '供应商H', qualityIssues: 2, qualityRate: 88 },
  { id: 3, name: '供应商I', qualityIssues: 4, qualityRate: 82 }
])

// 采购明细数据
const purchaseDetailData = ref([
  {
    orderNo: 'PO202401001',
    supplierName: '优质供应商A',
    productName: '笔记本电脑',
    category: '电子设备',
    quantity: 50,
    unitPrice: 5500,
    totalAmount: 275000,
    orderDate: '2024-01-15',
    deliveryDate: '2024-01-25',
    status: '已完成'
  },
  {
    orderNo: 'PO202401002',
    supplierName: '可靠供应商B',
    productName: '办公桌',
    category: '办公家具',
    quantity: 30,
    unitPrice: 800,
    totalAmount: 24000,
    orderDate: '2024-01-18',
    deliveryDate: '2024-01-28',
    status: '进行中'
  },
  {
    orderNo: 'PO202401003',
    supplierName: '稳定供应商C',
    productName: '打印纸',
    category: '办公用品',
    quantity: 200,
    unitPrice: 25,
    totalAmount: 5000,
    orderDate: '2024-01-20',
    deliveryDate: '2024-01-30',
    status: '待发货'
  }
])

// 方法
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '已完成': 'success',
    '进行中': 'primary',
    '待发货': 'warning',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const handleDateChange = () => {
  refreshData()
}

const refreshData = () => {
  ElMessage.success('数据已刷新')
}

const exportExcel = () => {
  ElMessage.success('Excel导出功能开发中')
}

const exportPDF = () => {
  ElMessage.success('PDF导出功能开发中')
}

const exportImage = () => {
  ElMessage.success('图片导出功能开发中')
}

const printReport = () => {
  window.print()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 初始化图表
const initCharts = () => {
  // 采购趋势图
  const purchaseTrend = echarts.init(purchaseTrendChart.value)
  purchaseTrend.setOption({
    title: {
      text: '月度采购金额趋势',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: ¥{c}万'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '采购金额(万元)'
    },
    series: [{
      data: [220, 180, 250, 280, 200, 320, 300, 350, 380, 360, 280, 300],
      type: 'line',
      smooth: true,
      itemStyle: { color: '#67C23A' },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(103, 194, 58, 0.3)'
          }, {
            offset: 1, color: 'rgba(103, 194, 58, 0.1)'
          }]
        }
      }
    }]
  })

  // 供应商分布
  const supplierDistribution = echarts.init(supplierDistributionChart.value)
  supplierDistribution.setOption({
    title: {
      text: '主要供应商采购占比',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c}万 ({d}%)'
    },
    series: [{
      name: '采购金额',
      type: 'pie',
      radius: '60%',
      data: [
        { value: 85, name: '优质供应商A' },
        { value: 65, name: '可靠供应商B' },
        { value: 48, name: '稳定供应商C' },
        { value: 35, name: '供应商D' },
        { value: 52, name: '其他供应商' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })

  // 采购类别分析
  const categoryAnalysis = echarts.init(categoryAnalysisChart.value)
  categoryAnalysis.setOption({
    title: {
      text: '采购类别分布',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: '{b}: ¥{c}万'
    },
    xAxis: {
      type: 'category',
      data: ['电子设备', '办公家具', '办公用品', '原材料', '其他']
    },
    yAxis: {
      type: 'value',
      name: '采购金额(万元)'
    },
    series: [{
      type: 'bar',
      data: [
        { value: 120, itemStyle: { color: '#409EFF' } },
        { value: 85, itemStyle: { color: '#67C23A' } },
        { value: 45, itemStyle: { color: '#E6A23C' } },
        { value: 65, itemStyle: { color: '#F56C6C' } },
        { value: 30, itemStyle: { color: '#909399' } }
      ]
    }]
  })

  // 成本分析
  const costAnalysis = echarts.init(costAnalysisChart.value)
  costAnalysis.setOption({
    title: {
      text: '采购成本构成',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}% ({d}%)'
    },
    series: [{
      name: '成本构成',
      type: 'pie',
      radius: ['40%', '70%'],
      data: [
        { value: 70, name: '产品成本', itemStyle: { color: '#409EFF' } },
        { value: 15, name: '运输费用', itemStyle: { color: '#67C23A' } },
        { value: 8, name: '税费', itemStyle: { color: '#E6A23C' } },
        { value: 5, name: '其他费用', itemStyle: { color: '#F56C6C' } },
        { value: 2, name: '管理费用', itemStyle: { color: '#909399' } }
      ],
      label: {
        show: true,
        formatter: '{b}: {c}%'
      }
    }]
  })
}

onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped>
.purchase-report {
  padding: 20px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.report-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.metrics-cards {
  margin-bottom: 20px;
}

.metric-card {
  text-align: center;
}

.metric-content {
  padding: 10px;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #67C23A;
  margin-bottom: 8px;
}

.metric-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.metric-change {
  font-size: 12px;
  font-weight: bold;
}

.metric-change.positive {
  color: #67C23A;
}

.metric-change.negative {
  color: #F56C6C;
}

.metric-change.neutral {
  color: #909399;
}

.charts-section {
  margin-bottom: 20px;
}

.performance-section {
  margin-bottom: 20px;
}

.performance-list {
  max-height: 200px;
  overflow-y: auto;
}

.performance-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f7fa;
}

.performance-item:last-child {
  border-bottom: none;
}

.supplier-info {
  flex: 1;
}

.supplier-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.supplier-detail {
  font-size: 12px;
  color: #909399;
}

.data-table-card {
  margin-top: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .report-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    flex-wrap: wrap;
  }
  
  .metrics-cards .el-col {
    margin-bottom: 10px;
  }
  
  .performance-section .el-col {
    margin-bottom: 20px;
  }
}
</style>